package com.tbvtc.agriculturalcreditchainserver2025.redis;

import com.tbvtc.agriculturalcreditchainserver2025.mapper.CartMapper;
import com.tbvtc.agriculturalcreditchainserver2025.vo.Cart.CartSelectUserByUserId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class OrderExpirationTask {
    @Autowired
    @Qualifier("cartRedisTemplate")

    private RedisTemplate<String, CartSelectUserByUserId> redisTemplate;
    @Autowired
    private CartMapper cartMapper;
    // 每分钟执行一次
    @Scheduled(fixedRate = 60_000)
    public void checkExpiredOrders() {
        ScanOptions options = ScanOptions.scanOptions()
            .match("order:*") // 匹配以 "order:" 开头的键
            .build();

        redisTemplate.execute((RedisCallback<Void>) connection -> {
            Cursor<byte[]> cursor = connection.scan(options); // 使用 RedisTemplate 的 execute 方法执行 Redis 操作
            while (cursor.hasNext()) {
                String key = new String(cursor.next()); // 将字节数组转换为字符串·
                Long ttl = redisTemplate.getExpire(key, TimeUnit.SECONDS); // 获取键的剩余过期时间
                if (ttl != null && ttl <= 0) {
                    handleExpiredOrder(key);
                    redisTemplate.delete(key);

                }
            }
            return null;
        });
    }

    private void handleExpiredOrder(String key) {
        // 与监听器相同的处理逻辑
        String orderId = key.split(":")[1]; // 获取用户 ID
        System.out.println("[定时任务]处理过期订单: " + orderId);
        cartMapper.removeCartByOrderId( key.split(":")[1]);
    }
}